<?php

namespace app\admin\controller;

use think\Db;
use think\Cache;

class Explore extends Common
{
    public function index()
    {
        $where = ['sys_channel'=>getenv('APP_CHANNEL')];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('explore')->where($where)->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);


        return $this->fetch();
    }

    public function add()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) {
                $post['sys_channel'] = getenv('APP_CHANNEL');
                $res = Db::name('explore')->insert($post);
                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $res = Db::name('explore')->where('id', $id)->update($post);
                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
    
            Cache::rm('task');
        } else {
            if ($id) {
                $name = Db::name('explore')->find($id);

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    return ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }

        return $data;
    }

    public function del()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = Db::name('explore')->delete($id);
    
                Cache::rm('task');
                
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }
}
